#!/usr/bin/python
#
# judger.py for neu-oj
# Copyright (C) 2011-2011 NEU-OJ Project
# Author: Philo Yang <ud1937@gmail.com>
# URL: <http://yangzhe1991.org/>
# For license information, see LICENSE.txt

# !!!!usually need sudo!!!!!
import socket
import os
import time

global key
key='fuckgre'
# a simple key,should be same to manager's
HOST = '127.0.0.1'    
# manager's ip
PORT = 23456 
while 1:
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#	print 'canjudge'
	s.sendto(key+'can judge',(HOST,PORT))
#	print 'sent'
	data,(host,port)=s.recvfrom(66666)
	if key!=data[:len(key)]:
		continue
	data=data[len(key):]
#	print data
	i=data.find('$$$$$')
	if i<0:
		continue
		s.close()
		time.sleep(2)
	submitid=data[:i]
	data=data[i+5:]
	i=data.find('$$$$$')
	if i<0:
		continue
		s.close()
		time.sleep(2)
	probid=data[:i]
	data=data[i+5:]
	i=data.find('$$$$$')
	if i<0:
		continue
		s.close()
		time.sleep(2)
	lang=int(data[:i])
	data=data[i+5:]
	i=data.find('$$$$$')
	if i<0:
		continue
		s.close()
		time.sleep(2)
	code=data[:i]
	data=data[i+5:]
	userid=data
	if lang==0:
		fname='Main.c'
	if lang==1:
		fname='Main.cc'
	if lang==2:
		fname='Main.pas'
	if lang==3:
		fname='Main.java'
	fp=open(fname,'w')
	fp.write(code)
	fp.close()
	#print code
	os.system('cp '+fname+' run0/')
	if code!='rejudge':
		os.system('./client_runner '+submitid+' '+userid+' '+probid+' '+str(lang))
	else:
		os.system('./client_runner '+submitid+' '+userid+' '+probid+' '+str(lang)+' '+'rejudge')

	s.close()
